import { contextBridge, ipcRenderer } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';

// Custom APIs for renderer
const api = {};

const invokes = ['open_config', 'get_ip_address', "get_copy"];
const handleInvocation = async (item) => {
  if (item === 'get_ip_address' || item === 'get_copy') {
    const result = await ipcRenderer.invoke(item);
    return result;
  } else {
    return ipcRenderer.invoke(item);
  }
};

for (const item of invokes) {
  api[item] = async () => {
    console.log('item', item);
    return handleInvocation(item);
  };
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI);
    contextBridge.exposeInMainWorld('api', api);
  } catch (error) {
    console.error(error);
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI;
  // @ts-ignore (define in dts)
  window.api = api;
}
